<template>
  <div class="asset-attachment-page">
    <el-card>
      <div style="margin-bottom: 16px; font-weight: bold;">资产附件管理</div>
      <el-form :inline="true" size="small" style="margin-bottom: 16px;">
        <el-form-item label="资产">
          <el-select v-model="assetId" placeholder="请选择资产" filterable clearable @change="fetchList">
            <el-option v-for="item in assetList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-upload
        v-if="assetId"
        :action="uploadUrl"
        :data="{ assetId }"
        :on-success="onUploadSuccess"
        :show-file-list="false"
        :headers="uploadHeaders"
        multiple
        drag
        style="margin-bottom: 16px;"
      >
        <el-icon><UploadFilled /></el-icon>
        <div>点击或拖拽上传附件</div>
      </el-upload>
      <el-table :data="list" border stripe style="width: 100%;">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="fileName" label="文件名" min-width="200" />
        <el-table-column prop="uploadTime" label="上传时间" min-width="160" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <a :href="scope.row.fileUrl" target="_blank">预览/下载</a>
            <el-button type="danger" size="small" @click="onDelete(scope.row)" style="margin-left: 8px;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!assetId" style="color: #888; margin-top: 32px;">请选择资产以管理附件</div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const assetList = ref([])
const assetId = ref(null)
const list = ref([])
const fetchAssetList = async () => {
  const res = await request.get('/asset/list')
  if (res.code === 1) {
    assetList.value = res.data
  }
}
const fetchList = async () => {
  if (!assetId.value) {
    list.value = []
    return
  }
  const res = await request.get('/asset/attachment/list', { params: { assetId: assetId.value } })
  if (res.code === 1) {
    list.value = res.data
  }
}
const uploadUrl = '/api/asset/attachment' // 需代理/api到后端
const uploadHeaders = {} // 如需token可补充
const onUploadSuccess = () => {
  ElMessage.success('上传成功')
  fetchList()
}
const onDelete = (row) => {
  ElMessageBox.confirm('确认删除该附件？', '提示', { type: 'warning' }).then(async () => {
    await request.delete(`/asset/attachment/${row.id}`)
    ElMessage.success('删除成功')
    fetchList()
  })
}
onMounted(() => {
  fetchAssetList()
})
</script>

<style scoped>
.asset-attachment-page {
  padding: 24px;
}
</style> 